const form = document.getElementById("form");
const errorDiv = document.getElementById("error");
const visDiv = document.getElementById("vis");
const uploadedFilesDiv = document.getElementById("uploadedFiles");
const fileInput = document.getElementById("dataFiles");
const fileListEl = document.getElementById("uploadedFilesList");
const dropZone = document.getElementById("dropZone");
const themeToggle = document.getElementById("themeToggle");
const uploadBtn = document.getElementById("uploadBtn");

let currentView = null;
let currentSpec = "";
let isDarkMode = false;

// 主题切换功能
themeToggle.addEventListener("click", () => {
  isDarkMode = !isDarkMode;
  document.body.classList.toggle("dark-mode", isDarkMode);
  localStorage.setItem("darkMode", isDarkMode);
});

uploadBtn.addEventListener("click", () => {
  fileInput.click();
});


// 初始化主题
function initTheme() {
  isDarkMode = localStorage.getItem("darkMode") === "true";
  document.body.classList.toggle("dark-mode", isDarkMode);
}

// 文件拖拽上传功能
dropZone.addEventListener("dragover", (e) => {
  e.preventDefault();
  dropZone.classList.add("dragover");
});

dropZone.addEventListener("dragleave", () => {
  dropZone.classList.remove("dragover");
});

dropZone.addEventListener("drop", (e) => {
  e.preventDefault();
  dropZone.classList.remove("dragover");

  if (e.dataTransfer.files.length) {
    fileInput.files = e.dataTransfer.files;
    const event = new Event("change", { bubbles: true });
    fileInput.dispatchEvent(event);
  }
});

// 文件上传处理
fileInput.addEventListener("change", async () => {
  showLoader(true, "正在上传文件...");
  errorDiv.textContent = "";
  fileListEl.innerHTML = "";

  const files = fileInput.files;
  if (files.length === 0) return;

  const formData = new FormData();
  for (let i = 0; i < files.length; i++) {
    formData.append("files", files[i]);
  }

  try {
    const res = await fetch("/upload", {
      method: "POST",
      body: formData,
    });

    const json = await res.json();
    if (res.ok) {
  const allFilesRes = await fetch("/uploaded_files");
  const allFilesJson = await allFilesRes.json();

  fileListEl.innerHTML = ""; // 清空旧列表

  allFilesJson.files.forEach((fname) => {
    const li = document.createElement("li");

    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.value = fname;
    checkbox.checked = true;
    li.appendChild(checkbox);

    const fileName = document.createElement("span");
    fileName.className = "file-name";
    fileName.textContent = fname;
    li.appendChild(fileName);

    // 添加 ❎ 删除按钮
    const delBtn = document.createElement("button");
    delBtn.textContent = "❎";
    delBtn.style.marginLeft = "10px";
    delBtn.style.color = "red";
    delBtn.style.border = "none";
    delBtn.style.background = "transparent";
    delBtn.style.cursor = "pointer";
    delBtn.onclick = async () => {
      if (confirm(`确定要删除文件 "${fname}" 吗？`)) {
        try {
          const res = await fetch("/delete_file", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ filename: fname }),
          });
          const result = await res.json();
          if (res.ok && result.success) {
            alert(`✅ 已删除: ${fname}`);
            li.remove(); // 从 DOM 中移除该行
          } else {
            alert("❌ 删除失败: " + (result.error || "未知错误"));
          }
        } catch (err) {
          alert("❌ 删除失败: " + err.message);
        }
      }
    };

    li.appendChild(delBtn);
    fileListEl.appendChild(li);
  });
}
 else {
      errorDiv.textContent = json.error || "文件上传失败";
    }
  } catch (err) {
    errorDiv.textContent = "上传失败: " + err.message;
  } finally {
    showLoader(false);
  }
});

// 提交生成图表请求
form.addEventListener("submit", async (e) => {
  e.preventDefault();
  errorDiv.textContent = "";
  visDiv.innerHTML = "";
  showLoader(true, "正在生成图表...");

  const description = document.getElementById("description").value.trim();
  if (!description) {
    errorDiv.textContent = "请填写图表描述";
    showLoader(false);
    return;
  }

  // 获取被勾选的文件名
  const selectedFiles = [];
  fileListEl.querySelectorAll("input[type=checkbox]").forEach((checkbox) => {
    if (checkbox.checked) {
      selectedFiles.push(checkbox.value);
    }
  });

  if (selectedFiles.length === 0) {
    errorDiv.textContent = "请选择至少一个文件用于生成图表";
    showLoader(false);
    return;
  }

  try {
    const res = await fetch("/generate_from_selected", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        selected_files: selectedFiles,
        text: description,
      }),
    });

    const json = await res.json();
    if (res.ok) {
      currentSpec = json.spec;
      const parsedSpec = JSON.parse(currentSpec);

      // 使用过渡效果渲染图表
      visDiv.style.opacity = 0;
      vegaEmbed("#vis", parsedSpec, { actions: false }).then((r) => {
        currentView = r.view;
        setTimeout(() => {
          visDiv.style.transition = "opacity 0.5s ease-in-out";
          visDiv.style.opacity = 1;
        }, 100);
      });
    } else {
      errorDiv.textContent = json.error || "生成图表失败";
    }
  } catch (err) {
    errorDiv.textContent = "请求异常: " + err.message;
  } finally {
    showLoader(false);
  }
});

// 加载动画控制
function showLoader(show, text = "") {
  const loader = document.getElementById("loader");
  const loaderText = document.getElementById("loaderText");

  if (show) {
    loader.style.display = "flex";
    loaderText.textContent = text;
  } else {
    loader.style.display = "none";
  }
}

// 下载功能
document.getElementById("downloadPNG").onclick = () => {
  if (currentView)
    currentView.toImageURL("png").then((url) => downloadFile(url, "chart.png"));
};

document.getElementById("downloadSVG").onclick = () => {
  if (currentView)
    currentView.toImageURL("svg").then((url) => downloadFile(url, "chart.svg"));
};

document.getElementById("copySpec").onclick = () => {
  navigator.clipboard.writeText(currentSpec).then(() =>
    alert("已复制 Vega-Lite JSON 配置")
  );
};

document.getElementById("downloadSpec").onclick = () => {
  const blob = new Blob([currentSpec], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  downloadFile(url, "chart_spec.json");
};

// 公共下载方法
function downloadFile(url, filename) {
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}